home *** CD-ROM | disk | FTP | other *** search
- Path: news.rain.org!usenet
- From: "Guus Leeuw jr." <guusl@eiffel.com>
- Newsgroups: comp.lang.c
- Subject: Re: scanf/gets interaction ?
- Date: Wed, 27 Mar 1996 15:38:02 -0800
- Organization: Interactive Software Engineering Inc. http://www.eiffel.com/
- Message-ID: <3159D15A.C2B4FA1@eiffel.com>
- References: <4j6joa$6ve@muller.loria.fr> <4jb7o2$5n1@rzsun02.rrz.uni-hamburg.de>
- NNTP-Posting-Host: @outback.eiffel.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; Linux 1.2.8 i586)
-
- Christian Duehl wrote:
- >
- > Denis B. Roegel (roegel@loria.fr) wrote:
- > : I have the following program:
- > :
- > : #include <stdio.h>
- > :
- > : main(){
- > : int n;
- > : char num[10];
- > : char*r;
- > : fflush(stdin);
- > : printf("n: ");scanf("%i",&n);
- > : printf("Numero ? ");r = gets(num);
- > : printf("Bien recu!\n");
- > : }
- > :
- > : which I compile with gcc on SunOS. The program asks for a first number n which
- > : I enter. But I never get a chance of entering a second one. Why is this so ?
- > :
- > Perhaps there is a loop missing :-)
-
- Nope that is not the point.
-
- >
- > (In K&R I read that fflush with an input stream has a not defined effect...)
- >
- > I think you could want your program so:
- >
- > #include <stdio.h>
- >
- > int main(void)
- > {
- > int n;
- > char num[10]; /* What happens if the input is longer than 9 chars???!!! */
- > char *r;
- >
- > /* fflush(stdin); */ /* undefined effect ... (K&R) */
- > printf("n: ");
- > scanf("%i",&n);
-
- The next line of code makes all the difference.
-
- > r = gets(num);
-
- > while (n>0) {
- > printf("Numero ? ");
- > r = gets(num);
- > printf("Bien recu!\n");
- > n--;
- > }
- >
- > return 0;
- > } /* main */
- >
-
- What happened in the original function is that scanf reads only the digits from stdin. It
- lets the newline (caused by the enter) in the input buffer. The gets(num) call reads that
- character from stdin and stdin is clear again. Now the user is able to type new characters.
-
- The moral of the story is: When using scanf to read numbers from stdin always remove the
- newline characters from stdin. `scanf' doesn't do that because that character is not a digit
- and thus scanf puts it back.
-
- Hope this explains,
- Guus
-